package lzj.tools;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.IDataSourceProvider;
import com.jfinal.plugin.activerecord.generator.Generator;
import com.jfinal.plugin.druid.DruidPlugin;
import javax.sql.DataSource;

public class SqlUtil {

  protected static final String[] DB_FORMATTERS = new String[]{"jdbc:mysql://%s:%d/%s?characterEncoding=%s&useSSL=false&autoReconnect=true&zeroDateTimeBehavior=convertToNull"};
  protected static final String[] DB_TYPE_NAMES = new String[]{"mysql"};

  //自动化生成映射文件
  public static boolean model(DataSource dataSource) {
    boolean result = false;
    String modelPackage = PropKit.get("model_package").trim()+".model";
    if (null != modelPackage && modelPackage.length() > 0) {
      String modelFolder = PathKit.getWebRootPath() + "/../src/main/java/" + modelPackage.replaceAll("\\.", "\\/");
      String baseFolder = modelFolder + "/base";
      String basePackage = modelPackage + ".base";
      Generator gen = new Generator(dataSource, basePackage, baseFolder, modelPackage, modelFolder);
      gen.setGenerateDaoInModel(PropKit.getBoolean("generate_dao_in_model"));
      gen.setGenerateDataDictionary(PropKit.getBoolean("generate_data_dictionary"));
      gen.setRemovedTableNamePrefixes(new String[]{"t_"});
      gen.generate();
      result = true;
    }

    return result;
  }

  private static DruidPlugin genDruidPlugin(SqlUtil.DBType type, String host, int port, String name, String encode, String user, String password, int max, int min, String validQuery) {
    String jdbcUrl = String.format(DB_FORMATTERS[type.ordinal()], host, port, name, encode);
    DruidPlugin druid = new DruidPlugin(jdbcUrl, user, password);
    druid.setMaxActive(max);
    druid.setMinIdle(min);
    druid.setInitialSize(min);
    druid.setRemoveAbandoned(true);
    druid.setRemoveAbandonedTimeoutMillis(1800 * 1000);
    if (StrKit.notBlank(validQuery)) {
      druid.setValidationQuery(validQuery);
    }
    WallFilter wall = new WallFilter();
    wall.setDbType(DB_TYPE_NAMES[type.ordinal()]);
    druid.addFilter(wall);
    druid.addFilter(new StatFilter());
    druid.start();
    return druid;
  }

  public static IDataSourceProvider dataSourcePlugin() {
    return genDruidPlugin(SqlUtil.DBType.MYSQL, PropKit.get("db_host"), PropKit.getInt("db_port"), PropKit.get("db_name"), PropKit.get("db_encode"), PropKit.get("db_user"), PropKit.get("db_pwd"), 15, 2, (String)null);
  }
  /**
   * 数据库类型
   */
  public enum DBType {
    MYSQL,
  }
}
